import cheerio from "cheerio";
import { eventHandler, EventCode } from "../event/eventHandler.js"
import { iArg } from "../iArg";
import { iFetcher } from "../iFetcher";
import { fetchRawData } from "./fetchRawData.js";

class ContestProblemsFetcher implements iFetcher {
    public data: contestProblems = new contestProblems();
    public async fetch(arg: iArg): Promise<string> {
        const { contestUrl,contestName } = arg;
        let htmlText: string = "";
        let requestUrl = contestUrl + "/tasks"
        htmlText = await fetchRawData(requestUrl)
        if (htmlText === "") {
            return ""
        }

        this.data.contestName=contestName as string
        try {
            let $ = cheerio.load(htmlText)("tbody").find("tr");
            if ($.length === 0) {
                throw new Error()
            }

            for (let i = 0; i < $.length; i++) {
                let t = new problem()
                t.order = $.eq(i).find("td").eq(0).text()
                t.name = $.eq(i).find("td").eq(1).text()
                t.timeLimit = $.eq(i).find("td").eq(2).text()
                t.memoryLimit = $.eq(i).find("td").eq(3).text()
                t.url = "https://atcoder.jp" + $.eq(i).find("td").eq(0).find("a").attr("href") as string
                this.data.problems.push(t);
            }
        } catch (e) {
            if (e instanceof Error) {
                eventHandler.handle(EventCode.PAESE_RAW_DATA_EXCEPTION,
                    `parse data from ${requestUrl} err`, new Error()
                )
            }
        }


        return JSON.stringify(this.data);
    }
}
class contestProblems {
    contestName: string = ""
    problems: problem[] = []

}

class problem {
    order: string = ""
    name: string = ""
    url: string = ""
    timeLimit: string = ""
    memoryLimit: string = ""
}


export { ContestProblemsFetcher };